#!/bin/sh
#
# Copyright 2015-2020 The OpenZipkin Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#

# ENTRYPOINT script that starts Cassandra
#
# This intentionally locates config using the current working directory, in order to consolidate
# Dockerfile instructions to WORKDIR
set -eu

# Apply one-time deferred configuration that relies on ENV variables
#
# If the schema has been removed due to mounting, restore from our backup. see: install
if [ ! -d data/zipkin2 ]; then
  cp -rf data-backup/* data/
fi

IP="$(hostname -i || echo '127.0.0.1')"
sed -i "s/127.0.0.1/${IP}/g" conf/cassandra.yaml

# Replace the logging level
sed -i "s/log4j.rootLogger.*/log4j.rootLogger=${LOGGING_LEVEL}, stdout/" conf/log4j.properties

# Use agent to allow instrumentation of a lambda: CASSANDRA-16304
JAMM_JAR=$(ls lib/jamm-*.jar)

# Configure the Docker HEALTHCHECK
export HEALTHCHECK_IP=${IP}
export HEALTHCHECK_PORT=9042
export HEALTHCHECK_KIND=tcp

echo Starting Cassandra
# -cp 'classes:lib/*' allows layers to patch the image without packaging or overwriting jars
#
# We also add exports and opens from Cassandra 4, except RMI, which isn't in our JRE image.
# See https://github.com/apache/cassandra/blob/cassandra-4.0-beta3/conf/jvm11-server.options
exec java -cp 'classes:lib/*' ${JAVA_OPTS} \
  -Xbootclasspath/a:${JAMM_JAR} -javaagent:${JAMM_JAR} \
  -Djdk.attach.allowAttachSelf=true \
  --add-exports java.base/jdk.internal.misc=ALL-UNNAMED \
  --add-exports java.base/jdk.internal.ref=ALL-UNNAMED \
  --add-exports java.base/sun.nio.ch=ALL-UNNAMED \
  --add-exports java.sql/java.sql=ALL-UNNAMED \
  --add-opens java.base/java.lang.module=ALL-UNNAMED \
  --add-opens java.base/jdk.internal.loader=ALL-UNNAMED \
  --add-opens java.base/jdk.internal.ref=ALL-UNNAMED \
  --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED \
  --add-opens java.base/jdk.internal.math=ALL-UNNAMED \
  --add-opens java.base/jdk.internal.module=ALL-UNNAMED \
  --add-opens java.base/jdk.internal.util.jar=ALL-UNNAMED \
  --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED \
  -Djava.io.tmpdir=/tmp \
  -Dcassandra-foreground=yes \
  -Dcassandra.storagedir=${PWD} \
  -Dcassandra.triggers_dir=${PWD}/triggers \
  -Dcassandra.config=file:${PWD}/conf/cassandra.yaml \
  -Dlog4j.configuration=file:${PWD}/conf/log4j.properties \
  org.apache.cassandra.service.CassandraDaemon "$@"
